package com.hrhr74.penguinstream.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrhr74.penguinstream.constant.UserConstant;
import com.hrhr74.penguinstream.domain.login.UserLogin;
import com.hrhr74.penguinstream.domain.po.User;
import com.hrhr74.penguinstream.mapper.UserMapper;
import com.hrhr74.penguinstream.service.LoginStrategy;
import com.hrhr74.penguinstream.utils.CodeUtil;
import com.hrhr74.penguinstream.utils.Result;
import com.hrhr74.penguinstream.utils.WriteTokenToRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service(UserConstant.Phone_LOGIN)
public class PhoneLogin extends ServiceImpl<UserMapper,User> implements LoginStrategy {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CodeUtil codeUtil;

    @Autowired
    private WriteTokenToRedis writeTokenToRedis;


    @Override
    public Result login(UserLogin userLogin) {
        if(userLogin==null){
            return Result.error("未知的登录方式！");
        }

        if(userLogin.getPhone()==null || userLogin.getCode()==null){
            return Result.error("未知的登录方式！");
        }
        //校验验证码
        if(!codeUtil.checkCode(userLogin.getPhone(),userLogin.getCode())){
            return Result.error("手机或验证码错误！");
        }

        User user = lambdaQuery().eq(User::getPhone, userLogin.getPhone()).one();
        if(user == null){
            //TODO 用户手机号注册
            return Result.error("用户不存在！");
        }
        //将token写入redis

        String key = UserConstant.LOGIN_KEY + user.getId();
        writeTokenToRedis.writeTokenToRedis(key,user.getId(),stringRedisTemplate);
        return Result.ok("登陆成功！");
    }
}
